package org.example.myframework.frame.demo.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5PasswordUtil {

    // 加密密码
    public static String encryptPassword(String password) {
        try {
            // 创建MD5加密对象
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 将密码转换为字节数组并进行加密
            byte[] byteData = md.digest(password.getBytes());

            // 将加密后的字节数组转换为十六进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : byteData) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 校验密码
    public static boolean verifyPassword(String inputPassword, String encryptedPassword) {
        // 将输入密码加密后与数据库中的加密密码进行比较
        return encryptPassword(inputPassword).equals(encryptedPassword);
    }

    public static void main(String[] args) {
        String originalPassword = "password123";
        String encryptedPassword = encryptPassword(originalPassword);
        System.out.println("加密后的密码：" + encryptedPassword);

        String inputPassword = "password123";
        System.out.println("密码校验结果：" + verifyPassword(inputPassword, encryptedPassword));
    }
}
